<?php
error_reporting(0);
class WeixinAction extends Action{
	private $token;
	private $data=array();
	private $my='AI9';
	public function index(){
		if(!defined('STATICS')){
			define ( 'STATICS', __ROOT__.'/Public/Common' );
		}
		
		$this->token=$this->_get('token');
		$weixin=new Wechat($this->token);
		$data=$weixin->request();
		$this->data=$weixin->request();
		$this->my=C('site_my');
		list($content,$type)=$this->reply($data);
		$this->saveWxMsg($content);
		$weixin->response($content,$type);
	}
	
	// 功能:记录用户地理位置到数据库

	public function RecordUserLocation2DB($msgType='event'){
		Log::write("记录用户地理位置信息到数据库",LOG::INFO);
		$wechatUserLocationMode=new Model("wxuserloc");
		$wechatUserLoc["token"]=$this->token;
		$wechatUserLoc["wechat_id"]=$this->data["FromUserName"];
		$wechatUserLoc["loc_time"]=time();
		
		switch($msgType){
			case 'event':
				$wechatUserLoc["location_x"]=$this->data["Longitude"];
				$wechatUserLoc["location_y"]=$this->data["Latitude"];
				$wechatUserLoc["precision"]=$this->data["Precision"];
				$wechatUserLoc["msg_type"]="event";
				break;
			case 'location':
				$wechatUserLoc["location_x"]=$this->data["Location_Y"];
				$wechatUserLoc["location_y"]=$this->data["Location_X"];
				$wechatUserLoc["precision"]='0';
				$wechatUserLoc["msg_type"]="location";
				break;
		}
		$wechatUserLocationMode->add($wechatUserLoc);
		Log::write("地理位置记录完毕",LOG::INFO);
	}
	
	private function saveWxMsg($content){
		
		// 存入请求
		// status:0表示未回复;1表示已经自动回复;2表示已经手动回复
		$wxmsg=M('wxmsg');
		$msg['token']=$this->token;
		$msg['msgtype']=$this->data['MsgType'];
		$msg['openid']=$this->data['FromUserName'];
		$msg['msgid']=$this->data['MsgId'];
		$msg['addtime']=time();
		$msg['manualtime']=time();
		
		if(is_array($content)){
			$msg['status']=1;
			$msg['response']=$this->msgdata2Str($content);
		}else{
			if($content=='回复帮助，可了解所有功能'){
				$msg['status']=0;
			}else{
				$msg['status']=1;
			}
			$msg['response']=$content;
		}
		
		if(stristr($this->data['MsgType'],'text')){
			$msg['msgcontent']=$this->data['Content'];
		} elseif(stristr($this->data['MsgType'],'image')){
			$msg['msgcontent'] = $this->data['PicUrl']; 
		} else{
			$msg['msgcontent']=$this->msgdata2Str($this->data);
		}
		$id = $wxmsg->add($msg);
		/*
		if(stristr($this->data['MsgType'],'image')){
			//如果是图片请求，下载图片信息并更新数据
			$url = U('Home/SaveMsg/saveImgmsg',array('id'=>$id));
			$fp = fsockopen('localhost',8011,$errno,$errstr);
			
			if(!$fp) {
				echo "$errstr ($errno)<br />/n";
			} else {
				$out = "GET $url \r\n";
				$out .= "Host: localhost\r\n";
				$out .= "Connection: Close\r\n\r\n";
				fwrite($fp, $out);
			}
			fclose($fp);
		}*/
	}
	
	private function msgdata2Str($data){
		$str='';
		foreach($data as $key=>$value){
			if(stristr($key,'ToUserName')||stristr($key,'FromUserName')||stristr($key,'CreateTime')||stristr($key,'MsgType')||stristr($key,'MsgId')){
			}else{
				if(is_array($value)){
					$str=$str.$key.'='.implode('.',$value).',';
				}else{
					$str=$str.$key.'='.$value.',';
				}
			}
		}
		return $str;
	}
	
	/**
	 *
	 * @param unknown $sceneId
	 *        	场景值
	 * @param unknown $ticket
	 *        	二维码票号
	 * @param unknown $scantype
	 *        	0为关注扫描进入，1为扫描进入
	 */
	private function SaveQrScanInfo($sceneId,$ticket,$wechaId,$scantype){
		$model=M('Qrcode_accessinfo');
		$token=$this->token;
		$data['access_time']=time();
		$data['qrscene_id']=$sceneId;
		$data['ticket']=$ticket;
		$data['access_wechat_id']=$wechaId;
		$data['token']=$token;
		$data['access_type']=$scantype;
		$result=$model->add($data);
		$log=$data['access_time']." ".$data['qrscene_id']." ".$data['ticket']." ".$data['access_wechat_id']." ".$data['token']." ".$data['access_type']." ".$result;
		Log::write("二维码扫描进入记录完毕".$log,LOG::INFO);
	}
	
	private function QrScan(){
		
	}
	
	private function reply($data){
		load('@.SubscribeHelper');

		$openid = $data['FromUserName'];
		
		if($data['Event']){
			// 菜单点击事件
			if('CLICK'==$data['Event']){
				$data['Content']=$data['EventKey'];
				Log::write("菜单点击事件, content=".$data['EventKey'],LOG::INFO);
			}
			
			if('LOCATION'==$data['Event']){
				// 高级接口用户地理位置事件
				Log::write("地理位置信息",LOG::INFO);
				$this->RecordUserLocation2DB();
				return array(
						'',
						'text');
			}
			
			//关注事件，只关心扫描关注事件
			if('subscribe'==$data['Event']){
				$qrtype=0;
				if($data['EventKey']){
					$info=substr($data['EventKey'],0,7);
					
					if($info=="qrscene"){
						$wechaId=$data['FromUserName'];
						$qrSceneId=substr($data['EventKey'],8);
						$ticket=$data['Ticket'];
						$this->SaveQrScanInfo($qrSceneId,$ticket,$wechaId,'0');
						
						$whr['scene_id'] = $qrSceneId;
						$whr['ticket'] = $ticket;
						$qr = M('qrcode')->where($whr)->field('id,typeid')->find();
						$qrtype = $qr['typeid'];
						
					}
				}

				SaveUserinfo($data['FromUserName'],$this->token, $qrtype);
				
				$welcomeMsg=$this->shouye($openid);
				
				if(!empty($welcomeMsg)){
					return $welcomeMsg;
				}
			}
			
			/*
			if('SCAN'==$data['Event']){
				$wechaId=$data['FromUserName'];
				$qrSceneId=$data['EventKey'];
				$ticket=$data['Ticket'];
				$this->SaveQrScanInfo($qrSceneId,$ticket,$wechaId,'1');
				$where['access_wechat_id'] = $wechaId;
				$ct = M('Qrcode_accessinfo')->where($where)->count();
				
				return array(
						'欢迎您的再次到来，您已签到'.$ct.'次',
						'text');
			}
			*/
		}
		
		
		
		/*
		if('subscribe'==$data['Event']){
			// 用户关注，记录用户数据
			//WechatAdvanceAPI::SaveUserinfo($data['FromUserName'],$this->token);
			SaveUserinfo($data['FromUserName'],$this->token);
			
			$info=substr($data['EventKey'],0,7);
			if($info=="qrscene"){
				$wechaId=$data['FromUserName'];
				$qrSceneId=substr($data['EventKey'],8);
				$ticket=$data['Ticket'];
				$this->SaveQrScanInfo($qrSceneId,$ticket,$wechaId,'0');
				return array(
					'感谢关注我们的公众帐号！',
					'text'
				);
			}
			
			$this->requestdata('follownum');
			
			return $this->welcome();
			
		}elseif('unsubscribe'==$data['Event']){
			// 用户取消关注，修改相应数据
			//WechatAdvanceAPI::SaveUnScribeUserinfo($data['FromUserName'],$this->token);
			SaveUnScribeUserinfo($data['FromUserName'],$this->token);
			$this->requestdata('unfollownum');
		}elseif('SCAN'==$data['Event']){
			// 高级接口扫描二维码进入公众平台获得的信息
			$wechaId=$data['FromUserName'];
			$qrSceneId=$data['EventKey'];
			$ticket=$data['Ticket'];
			$this->SaveQrScanInfo($qrSceneId,$ticket,$wechaId,'1');
			$where['access_wechat_id'] = $wechaId;
			$ct = M('Qrcode_accessinfo')->where($where)->count();
			return array(
					'欢迎您的再次到来，您已签到'.$ct.'次',
					'text');
		}*/
		
		Log::write("非订阅消息",LOG::INFO);

		$Pin=new GetPin();
		$key=$data['Content'];
		$open=M('Token_open')->where(array(
				'token'=>$this->_get('token')))->find();
		$this->fun=$open['queryname'];
		$datafun=explode(',',$open['queryname']);
		$tags=$this->get_tags($key);
		$back=explode(',',$tags);
		foreach($back as $keydata=>$data){
			$string=$Pin->Pinyin($data);
			if(in_array($string,$datafun)){
				$check=$this->user('connectnum');
				if($string=='fujin'){
					$this->recordLastRequest($key);
				}
				$this->requestdata('textnum');
				if($check['connectnum']!=1){
					$return=C('connectout');
					continue;
				}
				unset($back[$keydata]);
				eval('$return= $this->'.$string.'($back);');
				continue;
			}
		}
		if(!empty($return)){
			if(is_array($return)){
				return $return;
			}else{
				return array(
						$return,
						'text');
			}
		}else{
			// 处理关键词信息
			if($this->data["MsgType"]=="location"){
				Log::write("地理位置信息",LOG::INFO);
				$this->RecordUserLocation2DB('location');
				$this->recordLastRequest($this->data['Location_Y'].','.$this->data['Location_X'],'location');
				// $return = $this->GenerateLBSList($this->data);
				$locationX=$this->data['Location_Y'];
				$locationY=$this->data['Location_X'];
				Log::write("x=".$locationX." y=".$locationY,LOG::INFO);
				$return=$this->map($locationX,$locationY);
				return $return;
			}
			/*
			 * if($this->data['Location_X']){ Log::write("包含坐标",LOG::INFO); $this->recordLastRequest($this->data['Location_Y'].','.$this->data['Location_X'],'location'); return $this->map($this->data['Location_X'],$this->data['Location_Y']); } if(!(strpos($key,'开车去')===FALSE)||!(strpos($key,'坐公交')===FALSE)||!(strpos($key,'步行去')===FALSE)){ $this->recordLastRequest($key); $user_request_model = M('User_request'); $loctionInfo = $user_request_model->where(array( 'token'=>$this->_get('token'), 'msgtype'=>'location', 'uid'=>$this->data['FromUserName'] ))->find(); if($loctionInfo&&intval($loctionInfo['time']>(time()-60))){ $latLng = explode(',',$loctionInfo['keyword']); return $this->map($latLng[1],$latLng[0]); } return array( '请发送您所在的位置', 'text' ); }
			 */
			switch($key){
				
				case '首页':
					return $this->home();
					break;
				case '主页':
					return $this->home();
					break;
				case 'home':
					return $this->home();
					break;
				
				case '帮助':
					return $this->help();
					break;
				case 'help':
					return $this->help();
					break;
				
				
				
				default:
					
					return $this->keyword($key);
					/*
					$check=$this->user('diynum',$key);
					if($check['diynum']!=1){
						return array(
								C('connectout'),
								'text');
					}else{
						return $this->keyword($key);
					}
					*/
			}
		}
	}
	
	
	
	function shenhe($name){
		$name=implode('',$name);
		if(empty($name)){
			return '正确的审核帐号方式是：审核+帐号';
		}else{
			$user=M('Users')->field('id')->where(array(
					'username'=>$name))->find();
			if($user==false){
				return '主人'.$this->my."提醒您,您还没注册吧\n正确的审核帐号方式是：审核+帐号,不含+号";
			}else{
				$up=M('users')->where(array(
						'id'=>$user['id']))->save(array(
						'status'=>1,
						'viptime'=>strtotime("+1 day")));
				if($up!=false){
					return '主人'.$this->my.'恭喜您,您的帐号已经审核,您现在可以登陆平台测试功能啦!';
				}else{
					return '服务器繁忙请稍后再试';
				}
			}
		}
	}
	
	function keyword($key){
		$like['keyword']=array(
				'like',
				'%'.$key.'%');
		$like['token']=$this->token;
		$data=M('keyword')->where($like)->order('id desc')->find();
		
		if($data!=false){
			Log::write("data.".$data['module'],LOG::INFO);
			switch($data['module']){
				case 'Img':
					$this->requestdata('imgnum');
					$img_db=M($data['module']);
					$back=$img_db->field('id,text,pic,url,title')->limit(9)->order('id desc')->where($like)->select();
					$idsWhere='id in (';
					$comma='';
					
					$constrain['name']=array(
							'like',
							'%'.$key.'%');
					$constrain['token']=$this->token;
					$head_db=M('classify')->where($constrain)->limit(1)->find();
					if($head_db!=false){
						$return[]=array(
								$head_db['name'],
								$head_db['info'],
								$head_db['img'],
								'');
					}
					foreach($back as $keya=>$infot){
						$idsWhere.=$comma.$infot['id'];
						$comma=',';
						if($infot['url']!=false){
							if(!(strpos($infot['url'],'http')===FALSE)){
								$url=$infot['url'];
							}else{
								$urlInfos=explode(' ',$infot['url']);
								switch($urlInfos[0]){
									case '刮刮卡':
										$url=C('site_url').U('Wap/Guajiang/index',array(
												'token'=>$this->token,
												'wecha_id'=>$this->data['FromUserName'],
												'id'=>$urlInfos[1]));
										break;
									case '大转盘':
										$url=C('site_url').U('Wap/Lottery/index',array(
												'token'=>$this->token,
												'wecha_id'=>$this->data['FromUserName'],
												'id'=>$urlInfos[1]));
										break;
									case '商家订单':
										//$url=C('site_url').'/index.php?g=Wap&m=Host&a=index&token='.$this->token.'&wecha_id='.$this->data['FromUserName'].'&hid='.$urlInfos[1];
										$url=C('site_url').U('Wap/Host/index',array('token'=>$this->token,'wecha_id'=>$this->data['FromUserName'],'hid'=>$urlInfos[1]));
										break;
									case '优惠券':
										$url=C('site_url').U('Wap/Coupon/index',array(
												'token'=>$this->token,
												'wecha_id'=>$this->data['FromUserName'],
												'id'=>$urlInfos[1]));
										break;
								}
							}
						}else{
							$url=rtrim(C('site_url'),'/').U('Wap/Index/content',array(
									'token'=>$this->token,
									'id'=>$infot['id']));
						}
						$return[]=array(
								$infot['title'],
								$infot['text'],
								$infot['pic'],
								$url);
					}
					$idsWhere.=')';
					if($back){
						$img_db->where($idsWhere)->setInc('click');
					}
					return array(
							$return,
							'news');
					break;
				case 'Host':
					$this->requestdata('other');
					$host=M('Host')->where(array(
							'id'=>$data['pid']))->find();
					$url=C('site_url').U('Wap/Host/index',array(
							'token'=>$this->token,
							'wecha_id'=>$this->data['FromUserName'],
							'id'=>$data['pid']));
					return array(
							array(
									array(
											$host['name'],
											$host['info'],
											$host['ppicurl'],
											C('site_url').U('Wap/Host/index',array('token'=>$this->token,'wecha_id'=>$this->data['FromUserName'],'hid'=>$data['pid']))
								)),
							'news');
					//C('site_url').'/index.php?g=Wap&m=Host&a=index&token='.$this->token.'&wecha_id='.$this->data['FromUserName'].'&hid='.$data['pid'])),
					break;
				case 'Text':
					$this->requestdata('textnum');
					$info=M($data['module'])->order('id desc')->find($data['pid']);
					return array(
							htmlspecialchars_decode($info['text']),
							'text');
					break;
				
				case 'Selfform':
					$this->requestdata('other');
					$pro=M('Selfform')->where(array(
							'id'=>$data['pid']))->find();
					$url=C('site_url').U('Wap/Selfform/index',array(
							'token'=>$this->token,
							'wecha_id'=>$this->data['FromUserName'],
							'id'=>$data['pid']));
					return array(
							array(
									array(
											$pro['name'],
											strip_tags(htmlspecialchars_decode($pro['intro'])),
											$pro['logourl'],
											C('site_url').U('Wap/Selfform/index',array('token'=>$this->token,'wecha_id'=>$this->data['FromUserName'],'id'=>$data['pid']))
											)),
							'news');
					//C('site_url').'/index.php?g=Wap&m=Selfform&a=index&token='.$this->token.'&wecha_id='.$this->data['FromUserName'].'&id='.$data['pid']
					break;
				
				
				default:
					$this->requestdata('videonum');
					$info=M($data['module'])->order('id desc')->find($data['pid']);
					return array(
							array(
									$info['title'],
									$info['keyword'],
									$info['musicurl'],
									$info['hqmusicurl']),
							'music');
			}
		}else{
			/*
			$utf8key = urlencode($key);
			
			$opts = array(
				'http'=>array(
					'timeout'=>4,
				)
			);
			$context = stream_context_create($opts);
			
			//$qa = file_get_contents("http://192.168.0.5:9123/search/search.aspx?query=$utf8key&input-encoding=utf-8", false, $context);
			
			if(strlen($qa) > 5){
				return array(
					$qa,'text'
				);
			}*/

			//if(!strpos($this->fun,'liaotian')){
			if(true){
				$other=M('Other')->where(array(
						'token'=>$this->token))->find();
				if($other==false){
					return array(
							'回复帮助，可了解所有功能',
							'text');
				}else{
					if(empty($other['keyword'])){
						return array(
								$other['info'],
								'text');
					}else{
						$img=M('Img')->field('id,text,pic,url,title')->limit(5)->order('id desc')->where(array(
								'token'=>$this->token,
								'keyword'=>array(
										'like',
										'%'.$other['keyword'].'%')))->select();
						if($img==false){
							return array(
									'无此图文信息,请提醒商家，重新设定关键词',
									'text');
						}
						foreach($img as $keya=>$infot){
							if($infot['url']!=false){
								$url=$infot['url'];
							}else{
								$url=rtrim(C('site_url'),'/').U('Wap/Index/content',array(
										'token'=>$this->token,
										'id'=>$infot['id']));
							}
							$return[]=array(
									$infot['title'],
									$infot['text'],
									$infot['pic'],
									$url);
						}
						return array(
								$return,
								'news');
					}
				}
			}
			return array(
					$this->chat($key),
					'text');
		}
	}
	
	/**
	 * 关注时回复
	 */
	function welcome(){
		$where['keyword'] = 'welcome';
		$models = M('Img')->field('id,text,pic,url,title')->limit(9)->order('id asc')->where($like)->select();
		
		foreach ($models as $key=> $model){
			if($model['url'] != false){
				$url=$model['url'];
			}else{
				$url = C('site_url').U('Wap/Index/content',array(
								'token'=>$this->token,
								'id'=>$model['id']));
			}
			$returnArray[] = array(
					$model['title'],
					$model['text'],
					$model['pic'],
					$url,
			);
		}
		return array(
			$returnArray,
			'news',
		);
	}
	
	function home(){
		return $this->shouye();
	}
	function shouye($openid){

		$texts = M('areply')->where(array('keyword'=>''))->field('content')->limit(1)->select();
		
		//$sql=M('areply')->getLastSql();
		
		if(!empty($texts) && count($texts) > 0){
			return array(
					str_replace('openid_replace', $openid, $texts[0]['content']),
					'text'
			);
		}
		/*
		$home=M('Home')->where(array(
				'token'=>$this->token))->find();
		if($home==false){
			return array(
					'商家未做首页配置，请稍后再试',
					'text');
		}else{
			$this->requestdata('3g');
			$imgurl=$home['picurl'];
			if($home['apiurl']==false){
				$url=rtrim(C('site_url'),'/').U('Wap/Index/index',array(
						'token'=>$this->token,
						'wecha_id'=>$this->data['FromUserName']));
			}else{
				$url=$home['apiurl'];
			}
		}
		return array(
				array(
						array(
								$home['title'],
								$home['info'],
								$imgurl,
								$url)),
				'news');
		*/
	}
	
	function recordLastRequest($key,$msgtype='text'){
		$rdata=array();
		$rdata['time']=time();
		$rdata['token']=$this->_get('token');
		$rdata['keyword']=$key;
		$rdata['msgtype']=$msgtype;
		$rdata['uid']=$this->data['FromUserName'];
		$user_request_model=M('User_request');
		$user_request_row=$user_request_model->where(array(
				'token'=>$this->_get('token'),
				'msgtype'=>$msgtype,
				'uid'=>$rdata['uid']))->find();
		if(!$user_request_row){
			$user_request_model->add($rdata);
		}else{
			$rid['id']=$user_request_row['id'];
			$user_request_model->where($rid)->save($rdata);
		}
	}
	
	function liaotian($name){
		$name=array_merge($name);
		$this->chat($name[0]);
	}
	public function fistMe($data){
		if('event'==$data['MsgType']&&'subscribe'==$data['Event']){
			return $this->help();
		}
	}
	public function help(){
		$data=M('Areply')->where(array(
				'token'=>$this->token))->find();
		return array(
				preg_replace("/(\015\012)|(\015)|(\012)/","\n",$data['content']),
				'text');
	}
	function error_msg($data){
		return '没有找到'.$data.'相关的数据';
	}
	public function user($action,$keyword=''){
		$user=M('Wxuser')->field('uid')->where(array(
				'token'=>$this->token))->find();
		$usersdata=M('Users');
		$dataarray=array(
				'id'=>$user['uid']);
		$users=$usersdata->field('gid,diynum,connectnum,activitynum,viptime')->where(array(
				'id'=>$user['uid']))->find();
		$group=M('User_group')->where(array(
				'id'=>$users['gid']))->find();
		if($users['diynum']<$group['diynum']){
			$data['diynum']=1;
			if($action=='diynum'){
				$usersdata->where($dataarray)->setInc('diynum');
			}
		}
		if($users['connectnum']<$group['connectnum']){
			$data['connectnum']=1;
			if($action=='connectnum'){
				$usersdata->where($dataarray)->setInc('connectnum');
			}
		}
		if($users['viptime']>time()){
			$data['viptime']=1;
		}
		return $data;
	}
	public function requestdata($field){
		$data['year']=date('Y');
		$data['month']=date('m');
		$data['day']=date('d');
		$data['token']=$this->token;
		$mysql=M('Requestdata');
		$check=$mysql->field('id')->where($data)->find();
		if($check==false){
			$data['time']=time();
			$data[$field]=1;
			$mysql->add($data);
		}else{
			$mysql->where($data)->setInc($field);
		}
	}
	
	function httpGetRequest_baike($url){
		$headers=array(
				"User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1",
				"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
				"Accept-Language: en-us,en;q=0.5",
				"Referer: http://www.baidu.com/");
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
		$output=curl_exec($ch);
		curl_close($ch);
		if($output===FALSE){
			return "cURL Error: ".curl_error($ch);
		}
		return $output;
	}
	public function get_tags($title,$num=10){
		vendor('Pscws.Pscws4','','.class.php');
		$pscws=new PSCWS4();
		$pscws->set_dict(CONF_PATH.'etc/dict.utf8.xdb');
		$pscws->set_rule(CONF_PATH.'etc/rules.utf8.ini');
		$pscws->set_ignore(true);
		$pscws->send_text($title);
		$words=$pscws->get_tops($num);
		$pscws->close();
		$tags=array();
		foreach($words as $val){
			$tags[]=$val['word'];
		}
		return implode(',',$tags);
	}
}
?>